<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\WebPage;
use \StudyBuddy\Question;
use \StudyBuddy\Request;
use \StudyBuddy\Responder;

/**
 *
 * This contoller received the
 * "Close" form from the question
 * View and then depending on permission
 * of Viewer will either mark question
 * as closed or send request to close question
 * to Moderators
 *
 */
class Difficult extends WebPage
{
	protected $membersOnly = true;

	protected $requireToken = true;

	protected $aRequired = array('qid', 'dif');

	protected $oQuestion;

	protected function main(){
		$this->collection = 'QUESTIONS';
		$this->getQuestion()
		->setDif()
		->returnResult();
	}


	protected function getQuestion(){
		d('type: '.$this->collection);
		$coll = $this->oRegistry->Mongo->getCollection($this->collection);
		$a = $coll->findOne(array('_id' => (int)$this->oRequest['qid']));
		d('a: '.print_r($a, 1));

		if(empty($a)){
				
			throw new \StudyBuddy\Exception('Item not found');
		}

		$class = ('QUESTIONS' === $this->collection) ? '\\StudyBuddy\\Question' : '\\StudyBuddy\\Answer';

		$this->oQuestion = new $class($this->oRegistry, $a);

		return $this;
	}


	/**
	 *
	 * If moderator then close it,
	 * if Not moderator then if owner - request closing
	 * of question
	 *
	 * @return object $this
	 */
	protected function setDif(){
		$dif = $this->oRequest->get('dif', 's', '1');
		d('dif: '.$dif);

		$this->oQuestion->setDif($dif);

		return $this;

	}
	
	protected function returnResult(){
		/**
		 * @todo translate string
		 */
		$message = 'New dif set to ' . $this->oRequest->get('dif', 'i', '1');
		if(Request::isAjax()){
			$ret = array('reload' => 100); //'alert' => $message,
			Responder::sendJSON($ret);
		}

		Responder::redirectToPage($this->oQuestion->getUrl());
	}

}
